package com.example.project.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import com.example.project.XMLParser;

public class SQLiteValoracion extends SQLiteOpenHelper {
	//static final String URL = "http://www.rcardsp.tk/serviceValoracion.php";
	static final String URL = "https://sites.google.com/site/balaguerrcardsp/valoracions/valoracion.xml";
	static final String KEY_VALORACIO = "tupla"; 
	static final String KEY_IDRESTAURANT = "idComer"; 
 	static final String KEY_IDVALORACION = "idValoracion";
 	static final String KEY_NOTA="nota";
 	static final String KEY_COMENTARIO="comentario";
	static final String TABLE_NAME = "valoracion";
	
    public SQLiteValoracion(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
   
    String sqlCreate = "CREATE TABLE valoracion (" +
    		KEY_IDVALORACION + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
    		KEY_IDRESTAURANT + " INTEGER, " +
    		KEY_NOTA +  " TEXT, " +
    		KEY_COMENTARIO + " TEXT);";

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlCreate);
        this.init(db);
    }
 
    public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
        db.execSQL("DROP TABLE IF EXISTS valoracion");
        db.execSQL(sqlCreate);
    }
    
    private void init(SQLiteDatabase db){
    	XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL); 
		Document doc = parser.getDomElement(xml); 
		NodeList nl = doc.getElementsByTagName(KEY_VALORACIO);
		ContentValues values = new ContentValues(); 
    	
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = (Element) nl.item(i);
			values.put(KEY_IDRESTAURANT, parser.getValue(e, KEY_IDRESTAURANT));
			values.put(KEY_IDVALORACION, parser.getValue(e, KEY_IDVALORACION));
			values.put(KEY_NOTA, parser.getValue(e, KEY_NOTA));
			values.put(KEY_COMENTARIO, parser.getValue(e, KEY_COMENTARIO));
			

			// adding HashList to ArrayList
			db.insert(SQLiteValoracion.TABLE_NAME, null, values);
		}
		
    }		
}
